package com.example.product.controller;

import cn.hutool.core.io.FileUtil;
import com.example.product.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/files")
public class FileController {

    // 表示本地磁盘文件的存储路径
    @Value("${upload.filePath}")
    private String filePath;

    /**
     * 文件上传
     */
    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile multipartFile) {
        //1.判断文件是否为空
        if (multipartFile.isEmpty()) {
            return new Result(500, "文件上传失败", null);
        }
        //2.获取文件名称
        String fileName = multipartFile.getOriginalFilename();
        //3.获取图片后缀名称   图片1.png
        String fileLastName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        //4.重新生成图片名称,UUID 11323141.png
        String newFileName = System.currentTimeMillis() + fileLastName;
        //创建文件对象 e:/img
        File file = new File(filePath);
        //判断该目录下是否有此文件夹
        if (file.exists()) {
            file.mkdir();//创建文件夹
        }
        //将上传文件放入文件夹中
        try {
            //创建文件对象
            File fileImg = new File(filePath,newFileName);
            multipartFile.transferTo(fileImg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return new Result(200,"图片上传成功","/images/"+newFileName);
    }

    /**
     * 文件下载
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置下载文件http响应头
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8)));
        // 拼接完整的文件存储路径
        String realFilePath = filePath + fileName;
        try {
            // 通过文件的存储路径拿到文件字节数组
            byte[] bytes = FileUtil.readBytes(realFilePath);
            ServletOutputStream os = response.getOutputStream();
            // 将文件字节数组写出到文件流
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            System.out.println("文件下载错误");
        }
    }



}